using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using DICE_GS;

public class CharacterSelectSceneManager : LTEventListenerC {
	enum CharacterName
	{
		Dawool=1,
		Issad,
		Mana,
		Teharil,
		Fanny,
		Ruda
	};

    enum SceneAnimation
    {
        Anchor_UI_CharSelect_01_In,
        Anchor_UI_CharSelect_01_Out,
        Anchor_UI_CharSelect_02_In,
        Anchor_UI_CharSelect_02_Out_To_01,
        Anchor_UI_CharSelect_02_Out_To_03,
        Anchor_UI_CharSelect_03_In,
        Anchor_UI_CharSelect_03_Out_To_02,
        Anchor_UI_CharSelect_03_Out_To_04,
        Anchor_UI_CharSelect_04_End
    }

	public GameObject selectedFXPrefab;
	
	public GameObject[] characterObjects;
	
	public GameObject[] selectedFXList;
	
	public GameObject selectCharLabel;

	public GameObject backGorundObject;
	public GameObject characterSelectPanel;
	public GameObject characterDetailPanel;
	public GameObject inputUserNickNamePanel;

	public UILabel characterNameLabel;
	public UILabel characterDescLabel;
	public UISprite skill1Icon;
	public UISprite skill2Icon;
	public UILabel[] skill1Labels;
	public UILabel[] skill2Labels;

	public UISprite characterImage;
	public tk2dSpriteAnimator characterAnimation;
    
	public UIInput userNickNameInput;

	public Animator characterBarAnimator;
    public Animator sceneAnimator;

	public UILabel SelectedCharacterNameLabel;

    public UILabel noticeEmptyNickNameLabel;
    public UILabel noticeDuplicateNickNameLabel;

	int currentSelectedCharIndex = 0;
    int centerObjectIndex = 2;

	int[] characterNameStringId = new int[6]{2029, 2033, 2035, 2039, 2031, 2037};
	string[] charRightAnimName = new string[6]{"CharBarAni_DawoolA", "CharBarAni_issadA", "CharBarAni_ManaA", "CharBarAni_TeharilA", "CharBarAni_FannyA", "CharBarAni_RudaA" };
	string[] charLeftAnimName = new string[6]{"CharBarAni_DawoolA_return", "CharBarAni_IssadA_return", "CharBarAni_ManaA_return", "CharBarAni_TeharilA_return", "CharBarAni_FannyA_return", "CharBarAni_RudaA_return" };

	public GameObject[] cardImages;

	public tk2dSpriteAnimation[] characterAnimationData;
    public tk2dSpriteCollectionData[] characterSpriteCollectionData;

	private static Queue<Dictionary<byte, object>> packetQueue;

	void Awake()
	{
		packetQueue = new Queue<Dictionary<byte, object>>();
	}

	IEnumerator Co_PreMoveCharacter()
	{
		SelectedCharacterNameLabel.text = CStringTableManager.Instance.GetItemById(characterNameStringId[currentSelectedCharIndex]);
        //characterBarAnimator.Play(charLeftAnimName[currentSelectedCharIndex]);
        //characterBarAnimator.speed = 0;
        cardImages[2].collider.enabled = true;
		yield return null;
//		yield return new WaitForSeconds(0.5f);
//		currentSelectedCharIndex = 1;
//		SelectedCharacterNameLabel.gameObject.SetActive(false);
//		characterBarAnimator.Play(charLeftAnimName[currentSelectedCharIndex]);
//		currentSelectedCharIndex++;
	}
	
	// Use this for initialization
	void Start () {
//		characterBarAnimator.Play(charLeftAnimName[0]);
//		characterBarAnimator.Play(charLeftAnimName[1]);
//		characterBarAnimator.Play(charLeftAnimName[2]);
        StartCoroutine("Co_PreMoveCharacter");

        characterBarAnimator.speed = 2f;
	}
	
	// Update is called once per frame
	void Update () {
		
        //if (isFinishedLoadUserData && Tables.isLoadDone)
        //{
        //    CSceneManager.manager.GoToWaitroomScene();
        //}

		while (packetQueue.Count > 0)
		{
			Dictionary<byte, object> tmpPacket = packetQueue.Dequeue();

			switch ((byte)tmpPacket[0])
			{
				case (byte)OperationCodes.SC_LOGIN:
					{
						glog.debug("OP_LOGIN");
                        PC_SC_LOGIN packet = new PC_SC_LOGIN(tmpPacket);
						if (packet.LoginResult == (int)LoginResult.LR_NEW_USER)
						{
							CSceneManager c = GameObject.FindObjectOfType(typeof(CSceneManager)) as CSceneManager;
							c.GotoInputNicknameScene();
						}
						else if (packet.LoginResult == (int)LoginResult.LR_LOGIN_OK)
						{
                            CSceneManager.ServerType = packet.ServerType;

							LoadingWindow.window.ShowShortLoading();
//					        loadingText.text = CStringTableManager.Instance.GetItemById(1610);
					        RestAPI.singleton.RefreshUserData(ReturnCallback);
                            RestAPI.singleton.GetPVEStageInfo(ReturnCallback);

                            CSceneManager.NeedToDisconnect = true;   
						}
						else
						{
							glog.debug("Login Error!");
						}
					}
					break;
				default:
					glog.debug("LoadingSceneManager's Packet Handler Unknown Packet Recieved [" + (byte)tmpPacket[0] + "]");
					break;
			}
		}
	}
	
	public static bool PacketHandler(Dictionary<byte, object> _packet)
	{
		if (packetQueue != null)
		{
			packetQueue.Enqueue(_packet);
			return true;
		}

		return false;
	}
	
	int selectedIndex = -1;
	int prevSelectedIndex = -1;
	GameObject prevSelectedFXObj;
	public override void OnEvent (int eventID)
	{
		base.OnEvent (eventID);
		
//		selectCharLabel.SetActive(false);
		
		prevSelectedIndex = selectedIndex;
		selectedIndex = eventID;

		SetCharacterDetailInfo(eventID);
		
//		GameObject obj = Instantiate(selectedFXPrefab) as GameObject;
//		obj.transform.parent = characterObjects[eventID].transform;
//		obj.transform.localPosition = new Vector3(0f, 30f, -500f);
//		obj.transform.localScale = Vector3.one;
//		obj.GetComponent<ParticleSystem>().Play();
		
//		StartCoroutine("Co_PlayAnimation", eventID);
//		if( selectedIndex != prevSelectedIndex )
//		{
//			selectedFXList[eventID].SetActive(true);
//			selectedFXList[eventID].GetComponent<ParticleSystem>().Play();
//			
//			tk2dSpriteAnimator anim = characterObjects[eventID].GetComponent<tk2dSpriteAnimator>();
//			anim.Play();
//			
//			if( prevSelectedIndex > -1 )
//			{
//				anim = characterObjects[prevSelectedIndex].GetComponent<tk2dSpriteAnimator>();
//				anim.StopAndResetFrame();
//				anim.Stop();
//				selectedFXList[prevSelectedIndex].SetActive(false);
//				selectedFXList[prevSelectedIndex].GetComponent<ParticleSystem>().Stop();
//			}
//		}
//		else
//		{
//			if( selectedFXList[prevSelectedIndex].activeSelf )
//			{
//				tk2dSpriteAnimator anim = characterObjects[prevSelectedIndex].GetComponent<tk2dSpriteAnimator>();
//				anim.StopAndResetFrame();
////				StartCoroutine("Co_StopAnimationEndFrame", anim);
////				anim.Stop();
//				selectedFXList[prevSelectedIndex].SetActive(false);
//				selectedFXList[prevSelectedIndex].GetComponent<ParticleSystem>().Stop();
//				selectedIndex = prevSelectedIndex = -1;
//			}
//		}
		
//		prevSelectedFXObj = obj;
	}
	
	IEnumerator Co_StopAnimationEndFrame(tk2dSpriteAnimator anim)
	{
		for(int i=0; i<20; i++)
			Debug.LogError(anim.CurrentFrame);
		
		yield return null;
	}
	
	IEnumerator Co_PlayAnimation(int index)
	{
		yield return new WaitForSeconds(1f);
		
		tk2dSpriteAnimator anim = characterObjects[index].GetComponent<tk2dSpriteAnimator>();
		anim.Play();
	}
	
	public void CreateUser(string nickName)
	{
//		if( selectedIndex != -1 )
		{
			LoadingWindow.window.ShowShortLoading();
			RestAPI.singleton.CreateUser(ReturnCallback, nickName, currentSelectedCharIndex+1);
		}
//		else
//		{
//			selectCharLabel.SetActive(true);
//		}
	}

	void SetCharacterDetailInfo(int charIndex)
	{
		CCharacterData charData = CCharacterDataManager.Instance.GetCharacterData(charIndex);
        if ( charData != null )
        {
            CSkillData skillData = CSkillDataManager.Instance.FindSkillData(charData.skill_01);
            if (skillData != null)
                characterNameLabel.text = CStringTableManager.Instance.GetItemByName(charData.name_string);
            characterDescLabel.text = CStringTableManager.Instance.GetItemByName(charData.desc_string);
            if (skillData != null)
            {
                skill1Labels[1].text = CStringTableManager.Instance.GetItemByName(skillData.name_string);
                skill1Labels[2].text = CStringTableManager.Instance.GetItemByName(skillData.desc_string);
            }
            skillData = CSkillDataManager.Instance.FindSkillData(charData.skill_02);
            if (skillData != null)
            {
                skill2Labels[1].text = CStringTableManager.Instance.GetItemByName(skillData.name_string);
                skill2Labels[2].text = CStringTableManager.Instance.GetItemByName(skillData.desc_string);
            }
            //if (characterAnimation.CurrentClip != null)
            //    characterAnimation.CurrentClip.wrapMode = tk2dSpriteAnimationClip.WrapMode.Once;
            //characterAnimation.StopAndResetFrame();
            //characterAnimation.GetComponent<tk2dSprite>().SetSprite(characterSpriteCollectionData[charIndex - 1], 0);
            characterImage.spriteName = ((CharacterName)charIndex).ToString();
            characterAnimation.Library = characterAnimationData[charIndex - 1];
            characterAnimation.DefaultClipId = 0;
            //AnimatorStateInfo state = characterBarAnimator.GetCurrentAnimatorStateInfo(0);
            //state.
            //AnimationInfo[] infos = characterBarAnimator.GetCurrentAnimationClipState(0);
            //Debug.LogError(infos[0].clip.name);
            //infos[0].clip.
            //characterAnimation.Play(characterAnimation.Library.clips[characterAnimation.DefaultClipId]);
            //characterAnimation.CurrentClip.wrapMode = tk2dSpriteAnimationClip.WrapMode.Loop;

            StartCoroutine("Co_PlayCharacterAnimation");

            backGorundObject.SetActive(true);
            //characterSelectPanel.SetActive(false);
            //characterSelectPanel.transform.localPosition = new Vector3(0f, 1500f, 0f);
            //characterDetailPanel.transform.localPosition = new Vector3(0f, 0f, 0f);
            //characterDetailPanel.SetActive(true);
            //sceneAnimator.Play(Animator.StringToHash(SceneAnimation.Anchor_UI_CharSelect_01_Out.ToString()));
            //sceneAnimator.GetCurrentAnimatorStateInfo().
        }
        sceneAnimator.Play(Animator.StringToHash(SceneAnimation.Anchor_UI_CharSelect_01_Out.ToString()));
	}

    IEnumerator Co_PlayCharacterAnimation()
    {
        ArrayList clipList = new ArrayList();
        foreach (tk2dSpriteAnimationClip clip in characterAnimation.Library.clips)
        {
            if (clip.name.Contains("front"))
            {
                clipList.Add(clip);
            }
        }

        foreach (tk2dSpriteAnimationClip clip in clipList)
        {
            characterAnimation.Play(clip);
            while (characterAnimation.IsPlaying(clip)) { yield return null; }
            yield return new WaitForSeconds(0.3f);
        }
    }

	void OnClickedCharDetailOKButton()
	{
        //characterDetailPanel.SetActive(false);
        //inputUserNickNamePanel.SetActive(true);
        sceneAnimator.Play(Animator.StringToHash(SceneAnimation.Anchor_UI_CharSelect_02_Out_To_03.ToString()));
	}

	void OnClickedCharDetailCancelButton()
	{
        //if (characterAnimation.CurrentClip != null)
        //    characterAnimation.CurrentClip.wrapMode = tk2dSpriteAnimationClip.WrapMode.Once;
        characterAnimation.StopAndResetFrame();
        //characterBarAnimator.Play(charRightAnimName[currentSelectedCharIndex]);
		SelectedCharacterNameLabel.text = CStringTableManager.Instance.GetItemById(characterNameStringId[currentSelectedCharIndex]);
        //characterBarAnimator.speed = 0;
		backGorundObject.SetActive(false);
        //characterDetailPanel.SetActive(false);
        //characterDetailPanel.transform.localPosition = new Vector3(0f, 1500f, 0f);
        //characterSelectPanel.SetActive(true);
        //characterSelectPanel.transform.localPosition = new Vector3(0f, 0f, 0f);
        StopCoroutine("Co_PlayCharacterAnimation");
        sceneAnimator.Play(Animator.StringToHash(SceneAnimation.Anchor_UI_CharSelect_02_Out_To_01.ToString()));
	}

	void OnClickedCharSelectOKButton()
	{
        //characterDetailPanel.SetActive(true);
        //characterSelectPanel.SetActive(false);
        //characterSelectPanel.transform.localPosition = new Vector3(0f, 1500f, 0f);
	}
	
	void OnClickedCharSelectCancelButton()
	{
	}

	void OnClickedUserNickNameOKButton()
	{
        if (!string.IsNullOrEmpty(userNickNameInput.value))
        {
            noticeEmptyNickNameLabel.gameObject.SetActive(false);
            string nickName = userNickNameInput.value;
            char[] trimChar = { '|', '\r' };
            nickName = nickName.TrimEnd(trimChar);
            CreateUser(nickName);
        }
        else
        {
            noticeEmptyNickNameLabel.gameObject.SetActive(true);
        }
	}
	
	void OnClickedUserNickNameCancelButton()
	{
        //characterDetailPanel.SetActive(true);
		userNickNameInput.value = "";
        //inputUserNickNamePanel.SetActive(false);
        sceneAnimator.Play(Animator.StringToHash(SceneAnimation.Anchor_UI_CharSelect_03_Out_To_02.ToString()));
	}

	int direction = 0;
	public void OnClickedRightArrow()
	{
		{
			direction = 1;
			cardImages[3].collider.enabled = false;
            //SelectedCharacterNameLabel.gameObject.SetActive(false);
			cardImages[currentSelectedCharIndex].collider.enabled = false;
			characterBarAnimator.Play(charLeftAnimName[currentSelectedCharIndex]);
			characterBarAnimator.speed = 1;
			if( currentSelectedCharIndex < 5 )
				currentSelectedCharIndex++;
			else
				currentSelectedCharIndex = 0;

            SelectedCharacterNameLabel.text = CStringTableManager.Instance.GetItemById(characterNameStringId[currentSelectedCharIndex]);
		}
	}

	public void OnClickedLeftArrow()
	{
		{
            Debug.LogError(currentSelectedCharIndex);
			direction = -1;
			cardImages[3].collider.enabled = false;
            //SelectedCharacterNameLabel.gameObject.SetActive(false);
			cardImages[currentSelectedCharIndex].collider.enabled = false;
			characterBarAnimator.Play(charRightAnimName[currentSelectedCharIndex]);
			characterBarAnimator.speed = 1;
			if( currentSelectedCharIndex > 0 )
				currentSelectedCharIndex--;
			else
				currentSelectedCharIndex = 5;

            SelectedCharacterNameLabel.text = CStringTableManager.Instance.GetItemById(characterNameStringId[currentSelectedCharIndex]);
		}
	}

	public void SetCurrentCharName()
	{
		SelectedCharacterNameLabel.text = CStringTableManager.Instance.GetItemById(characterNameStringId[currentSelectedCharIndex]);
		SelectedCharacterNameLabel.gameObject.SetActive(true);
        if (direction == 1)
        {
            cardImages[2].collider.enabled = true;
            cardImages[3].collider.enabled = true;
            cardImages[4].collider.enabled = true;
        }
        else if (direction == -1)
        {
            cardImages[0].collider.enabled = true;
            cardImages[1].collider.enabled = true;
            cardImages[2].collider.enabled = true;
        }
        shouldDrag = false;
	}

	public void OnClickedCharacterCard(GameObject obj)
	{
        Debug.LogError(obj.name + " -- " + direction);
//		System.Array ar = System.Enum.GetValues(typeof(CharacterName));
        if( obj.name.Equals(cardImages[0].name) || (obj.name.Equals(cardImages[2].name) && direction == 1) )
        {
            OnClickedLeftArrow();
            return;
        }
        else if ((obj.name.Equals(cardImages[2].name) && direction == -1) || obj.name.Equals(cardImages[4].name))
        {
            OnClickedRightArrow(); 
            return;
        }

		foreach(CharacterName name in System.Enum.GetValues(typeof(CharacterName)))
		{
            if (obj.GetComponent<SpriteRenderer>().sprite.name.Contains(name.ToString()))
            {
                SetCharacterDetailInfo((int)name);
                selectedIndex = (int)name;
            }
		}
	}

    bool shouldDrag = false;
    public void OnDrag(Vector2 delta)
    {
        Debug.LogError("DRAG!");
        if (!shouldDrag)
        {
            shouldDrag = true;
            if (delta.x > 0)
                OnClickedRightArrow();
            else
                OnClickedLeftArrow();
        }
    }
	
	bool isFinishedLoadUserData = false;
	void ReturnCallback(Hashtable returnData)
	{
		switch((RestAPIProtocol)returnData["protocol"])
		{
		case RestAPIProtocol.CREATEUSER:
            if (!returnData.ContainsKey("status"))
            {
                RestAPI.singleton.SetCurrentCharacter(ReturnCallback, selectedIndex);
                sceneAnimator.Play(Animator.StringToHash(SceneAnimation.Anchor_UI_CharSelect_04_End.ToString()));
            }
            else if (int.Parse(returnData["status"].ToString()) == 409)
            {
                LoadingWindow.window.HideLoading();
                noticeDuplicateNickNameLabel.gameObject.SetActive(true);
                userNickNameInput.value = "";
            }
            else
                ;  
			break;
		case RestAPIProtocol.SETCURRENTCHARACTER:
            Debug.LogError("returnCallback - RestAPIProtocol.SETCURRENTCHARACTER");
			CSceneManager.SendLoginPacket();
			break;
		case RestAPIProtocol.REFRESHUSERINFO:
            RestAPI.singleton.GetCurrentStaminaInfo(ReturnCallback);
            break;
        case RestAPIProtocol.GETCURRENTSTAMINAINFO:
//            loadingText.text = CStringTableManager.Instance.GetItemById(1609);
            RestAPI.singleton.GetMyUnitList(ReturnCallback);
            break;
        case RestAPIProtocol.GETMYUNITLIST:
//            loadingText.text = CStringTableManager.Instance.GetItemById(1608);
            RestAPI.singleton.RefreshMyDeckInfo(ReturnCallback);
            break;
        case RestAPIProtocol.REFRESHMYDECKINFO:
//            loadingText.gameObject.SetActive(false);
            isFinishedLoadUserData = true;
            CSceneManager.manager.GoToWaitroomScene();
            break;
        case RestAPIProtocol.PUTUSERDATA:
            break;
        case RestAPIProtocol.GETPVESTAGEINFO:
            break;
		}
	}
}
